package com.vr.cloudpicture.manager.sharding;

import org.apache.shardingsphere.sharding.api.sharding.standard.PreciseShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.RangeShardingValue;
import org.apache.shardingsphere.sharding.api.sharding.standard.StandardShardingAlgorithm;

import java.util.Collection;
import java.util.Collections;
import java.util.Properties;

/**
 * 图片表分表算法
 *
 * @author hzh
 * @date 2025/05/27
 */
public class PictureShardingAlgorithm implements StandardShardingAlgorithm<Long> {
    @Override
    public String doSharding(Collection<String> availableNames, PreciseShardingValue<Long> preciseShardingValue) {
        // 分表依据
        Long spaceId = preciseShardingValue.getValue();
        // 对那个表进行分表
        String logicTableName = preciseShardingValue.getLogicTableName();
        // spaceId为null时，查询逻辑的所有图片
        if (spaceId == null) {
            return logicTableName;
        }
        // 根据spaceId动态生成表名
        String realTableName = logicTableName + "_" + spaceId;
        // 判断生成表名是否可用，根据配置actual-data-nodes: yu_picture.picture来判断的
        // 因为是动态分表，需要让actual-data-nodes这个配置的值发生改变,要不然这里一直是picture,没办法返回真实表
        if (availableNames.contains(realTableName)) {
            return realTableName;
        } else {
            return logicTableName;
        }
    }

    @Override
    public Collection<String> doSharding(Collection<String> collection, RangeShardingValue<Long> rangeShardingValue) {
        return Collections.emptyList();
    }

    @Override
    public Properties getProps() {
        return null;
    }

    @Override
    public void init(Properties properties) {

    }
}
